<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 引入公共组件 -->
      <page-tools>
        <template v-slot:left>
          当前页面共{{ total }}条数据
        </template>
        <template v-slot:right>
          <el-button type="primary" plain @click="addRolesBtn">新增员工</el-button>
          <el-button v-premission="'export_excel'" type="success" size="mini">导出excel</el-button>
          <el-button v-premission="'import_excel'" type="success" size="mini" @click="exportExcel">导出excel</el-button>
        </template>
      </page-tools>
      <el-table border :data="tableData" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
        <el-table-column label="序号" type="index" />
        <el-table-column label="头像" prop="staffPhoto" width="180">
          <template slot-scope="scope">
            <!-- <img :src="scope.row.staffPhoto" width="100"> -->
            <!-- 在我们写媒体的时候， 一般element-ui会提供一些组件 el-image -->
            <!-- 二次封装组件，是项目公用的组件，需要放components里面 -->
            <!-- <img :src="scope.row.staffPhoto" width="100"> -->
            <ImgPreview :src="scope.row.staffPhoto" />
          </template>
        </el-table-column>

        <el-table-column label="姓名" prop="username" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template slot-scope="scope">
            <div @click="fn(scope)">{{ transfromHireType(scope.row.formOfEmployment) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" sortable prop="timeOfEntry" />
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="$router.push(`/employees/detail?id=${scope.row.id}`)"
            >查看</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="fenpeiRole(scope.row.id)"
            >分配角色</el-button>
            <el-button type="text" size="small" @click="delRoelBtn(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <span class="demonstration">显示总数</span>
        <el-pagination
          :current-page.sync="pageInfo.page"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 弹出框组件 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <DialogEmp v-if="dialogVisible" @close="dialogVisible=false" @updateSuccess="updateSuccess" />
    </el-dialog>
    <!-- 分配角色的权限弹窗 -->
    <el-dialog
      v-if="roleDialogVisble"
      title="分配角色"
      :visible.sync="roleDialogVisble"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <assign-role :current-id="currentId" @close="(roleDialogVisble=false)" />
    </el-dialog></div>
</template>

<script>
import AssignRole from './AssignRole.vue'
import { getUserListRequest, delUserListRequestById } from '@/api/employess'
import globalConstant from '@/constant/employees'
import DialogEmp from './dialog-emp'
import { transformEnToZhCN } from '@/utils'

// function test(id) {
//   const item = globalConstant.hireType.find(item => item.id === id)
//   if (item) {
//     return item.value
//   } else {
//     return '临时工'
//   }
// }
// console.log(test(2))

export default {
  components: {
    DialogEmp,
    AssignRole
  },
  data() {
    return {
      tableData: [],
      pageInfo: {
        page: 1,
        size: 10
      },
      total: 0, // 页面总数
      dialogVisible: false, // 弹出框是否关闭
      // 分配角色的弹框，显示隐藏属性
      roleDialogVisble: false,
      currentId: ''
    }
  },
  computed: {
    // 最后一页是否满了
    isLastPageFull() {
      return this.total % this.pageInfo.size === 0
    },
    maxPageNum() {
      return Math.ceil(this.total / this.pageInfo.size)
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    handleSizeChange(val) {
    },
    handleCurrentChange(value) {
    // 参数就是当前页码值
    // console.log(value)
    // 在js里面 将数据page的值 手动赋值为 当前最新的页码值， 再发请求
      this.pageInfo.page = value
      this.getUserList()
    },
    // 获得列表异步请求
    async getUserList() {
      try {
        const res = await getUserListRequest(this.pageInfo)
        if (res.success) {
          this.total = res.data.total
          this.tableData = res.data.rows
        }
      } catch (error) {
        this.$message.error('获取员工列表失败')
      }
    },
    // 枚举查找处理函数
    transfromHireType(id) {
    // 数组里面查找元素  find
    // const item = globalConstant.hireType.find(item => item.id === id)
    // if (item) {
    //   return item.value
    // } else {
    //   return '临时工'
    // }
      const obj = {}
      globalConstant.hireType.forEach(item => {
        obj[item.id] = item.value
      })
      return obj[id] ? obj[id] : '临时工'
    },
    // 点击新增
    addRolesBtn() {
      this.dialogVisible = true
      // console.log(111)
    },
    // 点击关闭
    handleClose() {
      this.dialogVisible = false
    },
    // 抛出的新增成功
    updateSuccess() {
      // 最后一页满了则跳转加一页
      if (this.isLastPageFull) {
        this.total++
        this.pageInfo.page = this.maxPageNum + 1
      } else {
        this.pageInfo.page = this.maxPageNum
      }
      this.dialogVisible = false
      this.getUserList()
    },
    // 点击删除
    delRoelBtn(params) {
      console.log(params)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delUserListRequestById(params)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.dialogVisible = false
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 异步删除
    async delUserListRequestById(id) {
      try {
        const res = await delUserListRequestById(id)
        console.log('delUserListRequestById: ', res)
      } catch (err) {
        console.log('delUserListRequestById: ', err)
      }
    },
    // 导出excel的方法
    exportExcel() {
      // 使用之前需要先下载两个包 file-saver script-loader
      // 要么使用 npm install file-saver script-loader
      // 要么使用 yarn add file-saver script-loader  两种方式二选一
      // console.log(this.tableData) // 服务器返回的 原始数据
      // const res = transformEnToZhCN(this.tableData) // 被我们转换过后的 excel需要的新数据
      import('@/vendor/Export2Excel').then(excel => {
        const { header, data } = transformEnToZhCN(this.tableData)
        excel.export_json_to_excel({
          // header: ['姓名', '年龄', '住址'],
          header,
          // data: [
          //   ['刘备', 500, '蜀国'],
          //   ['刘备1', 5001, '蜀国1'],
          //   ['刘备2', 5002, '蜀国2'],
          //   ['刘备3', 5003, '蜀国3']
          // ],
          data,
          filename: '导出文件的名称',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 点击分配角色
    fenpeiRole(id) {
      this.roleDialogVisble = true
      this.currentId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table{
  margin-top: 30px;
}
</style>
